#include <iostream>
 
#include "cv.h"
#include "highgui.h"
//#include "motion.h"

using namespace std;
void motion(IplImage*,IplImage*,IplImage*,IplImage* );
int main(){
   // cvNamedWindow("My Window", CV_WINDOW_AUTOSIZE);
    CvCapture * pCapture = 0;
    pCapture = cvCaptureFromCAM(0);
    IplImage  * pVideoFrame = 0;
    bool first = true;
     CvSize imgSize;
    imgSize.width = 640;
    imgSize.height = 480;
    IplImage* grey = cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
    
    IplImage* movingAverage = cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
    IplImage* difference=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
    IplImage* temp=cvCreateImage( imgSize, IPL_DEPTH_32F, 3);
    for(;;){
      pVideoFrame=cvQueryFrame(pCapture);
       if(first){
          difference = cvCloneImage(pVideoFrame);
          temp = cvCloneImage(pVideoFrame);
          cvConvertScale(pVideoFrame, movingAverage, 1.0, 0.0);
          first = false;
       }else{
         cvRunningAvg(pVideoFrame, movingAverage, 0.020, NULL);
       }
      
      motion(pVideoFrame,movingAverage,difference,temp);
     //   cvShowImage("My Window", grey);
     //   cvWaitKey(5);
    }
   // cvDestroyWindow("My Window");
    cvReleaseImage(&temp);
    cvReleaseImage(&difference);
    cvReleaseImage(&movingAverage);
    cvReleaseCapture(&pCapture);
     cvReleaseImage(&pVideoFrame);
          cvReleaseImage(&grey);
}

void motion(IplImage* colourImage,IplImage* movingAverage,IplImage* difference,IplImage* temp){ // Kameradan gelen Frame olacak!!!!!!!

    int say;

 CvSize imgSize;
 imgSize.width = colourImage->width;
 imgSize.height = colourImage->height;

 IplImage* greyImage = cvCreateImage( imgSize, IPL_DEPTH_8U, 1);

 
  //Convert the scale of the moving average.
  cvConvertScale(movingAverage,temp, 1.0, 0.0);
 
  //Minus the current frame from the moving average.
  cvAbsDiff(colourImage,temp,difference);
  
  //Convert the image to grayscale.
  cvCvtColor(difference,greyImage,CV_RGB2GRAY);
  
  //Convert the image to black and white.
  cvThreshold(greyImage, greyImage, 70, 255, CV_THRESH_BINARY);
  
  //Dilate and erode to get people blobs
  cvDilate(greyImage, greyImage, 0, 10);
  cvErode(greyImage, greyImage, 0, 10);
   say=cvCountNonZero(greyImage);
   
 // cvShowImage("My Window", greyImage);
  bool is_motion = false;  
  cout << "say=" <<say<<"\n";
  if(38400<=say){
        cout<<"Hareket var\n "<<say<<"\n";
        is_motion = true;
  }
    
 
  //Wait for the user to see it.
 // cvWaitKey(100);
  
//}
//cvDestroyWindow("My Window");
// cvReleaseImage(&temp);
// cvReleaseImage(&difference);
// cvReleaseImage(&movingAverage);
// cvReleaseImage(&greyImage);

    }
